<?
global $db;
global $user;
global $config;

$e = $db->query1("select * from {$this->table} where id = ".$db->sqlint($this->id));
$pe = $db->query1("select * from project where id = ".$db->sqlint($e["project_id"]));

inc_inclib("mail.php");

if (!isset($mode)) $mode = "updated";

#HACK: if it's a client we'll un-delegate them...
if (in_array("client",$user["groups"]) && 
	$e["status"] == "open" && 
	$e["delegate_users_id"] == $user["id"]) {
	$e["delegate_users_id"] = -1;
	}

if ($e["delegate_users_id"]<=0 && !$e["assign_users_id"]<=0) {
	$e["delegate_users_id"] = $pe["manager_users_id"];
	}
elseif ($e["delegate_users_id"]<=0) {
	$e["delegate_users_id"] = $e["assign_users_id"];
	}
	
$db->autoquery("update",$this->table,$e);

if ($mode == "updated" && $e["delegate_users_id"] != $params["_record"]["delegate_users_id"]) 
	$mode = "delegated";
	
if ($mode == "updated") return; #nobody cares, a message will be sent if someone should care.

$m = strtoupper(substr($mode,0,1));

/*
ob_start();
print_r($e);
$content = ob_get_contents();
ob_end_clean();
*/

$subject = "{$config["mail.prefix"]}{$user["title"]} - $m: {$e["title"]}";

$message = "A {$params["item"]} has been $mode by {$user["title"]}.\n".
	"{$pe["title"]}: {$e["title"]}\n\n".
#	"$content\n".
	"Please do not reply to this e-mail, instead go to\n".
	"{$GLOBALS["topurl"]}/";

//choose users to email
$to = array();
#$uid = $e["submit_users_id"];
#$to[$uid] = $uid;
$uid = $e["delegate_users_id"];
$to[$uid] = $uid;
$uid = $user["id"];
unset($to[$uid]);

//email them
inc_inclib("mail.php");
foreach ($to as $uid) {
	$ue = $db->query1("select * from users where id = ".$db->sqlint($uid));
	
	mail_send(array(
		"subject"=>$subject,
		"from"=>$config["mail.noreply"],
		"to"=>$ue["email"],
		"message"=>$message,
		));
	}

?>